import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author DASK
 * @date 2020/3/17 22:59
 * @description //TODO 请求过滤器
 */
public class RequestFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        boolean isLogin = false;
        for (Cookie cookie : request.getCookies()) {
            if ("isLogin".equals(cookie.getName())) {
                if ("1".equals(cookie.getValue())) isLogin = true;
            }
        }
        //判断是否登录，如果登录则允许访问站内其他资源
        if (isLogin) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //如果没有登录，则默认只能访问登录界面
            String path = request.getRequestURL().toString();
            String[] paths = path.split("/");
            String target = paths[paths.length - 1];
            //判断访问的是否是登录界面
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            //访问登录界面则放行请求
            if ("login".equals(target) || "login.jsp".equals(target)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                //访问其他路径一律重定向到登录界面
                response.setContentType("text/html;charset=UTF-8");
                response.sendRedirect("/login");
            }
        }
    }
}
